package com.dudu.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dudu.cache.Cache;
import com.dudu.model.User;
import com.dudu.model.dto.Token;
import com.dudu.util.Const;
import com.google.common.collect.Maps;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * Created by dudu on 2016/12/4.
 */
@Slf4j
@Service
public class HxService {

    @Resource
    private Cache cache;

    private String HxServer = "https://a1.easemob.com";

    public Token getToken() throws UnirestException {
        if(cache.exists(Const.APPID)) {
            return (Token) cache.getValue(Const.APPID);
        } else {
            HttpResponse<JsonNode> response;
            Map<String, Object> params = Maps.newHashMapWithExpectedSize(4);
            params.put("grant_type", "client_credentials");
            params.put("client_id", Const.APPID);
            params.put("client_secret", Const.SECRET);

            String jsonObject = JSON.toJSONString(params);
            for (int i = 0; i < 3; i++) {
                response = Unirest.post(String.format(HxServer + "/%s/%s/token", Const.ORG_NAME, Const.APP_NAME)).
                    header("Content-Type", "application/json").body(jsonObject).asJson();
                log.info("request get token with params {}, response {}", params, response);
                if (response.getStatus()== HttpStatus.SC_OK) {
                    Token token = JSONObject.parseObject(response.getBody().getObject().toString(), Token.class);
                    if(token != null) {
                        cache.add("_hx_token_", token, Long.valueOf(token.getExpires_in()));
                        return token;
                    }
                }

                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }
        return null;
    }
    
    public boolean register(User user) throws UnirestException {
        
        HttpResponse<JsonNode> response;
        Map<String, Object> params = Maps.newHashMapWithExpectedSize(4);
        params.put("username", user.getMobile());
        params.put("password", user.getPassword());
        params.put("nickname", user.getName());

        Token token = this.getToken();
        String jsonObject = JSON.toJSONString(params);
        for (int i = 0; i < 3; i++) {
            response = Unirest.post(HxServer + "/chatdemoui/users").
                    header("Content-Type", "application/json").header("Authorization", "Bearer " + token.getAccess_token()).body(jsonObject).asJson();
            log.info("request register with params {}, response {}", params, response);
            if (response.getStatus()== HttpStatus.SC_OK) {
                return true;
            }

            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        return false;
    }
    
    public boolean isOnline(String mobile) throws UnirestException{
        HttpResponse<JsonNode> response;

        Token token = this.getToken();
        Map<String, String> map = Maps.newHashMapWithExpectedSize(2);
        map.put("Content-Type", "application/json");
        map.put("Authorization", "Bearer " + token.getAccess_token());
        for (int i = 0; i < 3; i++) {
            response = Unirest.get(String.format(HxServer + "/%s/%s/users/%s/status", Const.ORG_NAME, Const.APP_NAME, mobile)).
                    headers(map).asJson();
            if (response.getStatus()== HttpStatus.SC_OK) {
                return true;
            }

            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        return false;
        
    }

    /**
     * 获取好友
     * @param mobile
     * @return
     * @throws UnirestException
     */
    public List<String> getFriends(String mobile) throws UnirestException{
        HttpResponse<JsonNode> response;

        Token token = this.getToken();
        Map<String, String> map = Maps.newHashMapWithExpectedSize(1);
        map.put("Authorization", "Bearer " + token.getAccess_token());
        for (int i = 0; i < 3; i++) {
            response = Unirest.get(String.format(HxServer + "/%s/%s/users/%s/contacts/users", Const.ORG_NAME, Const.APP_NAME, mobile)).
                headers(map).asJson();
            if (response.getStatus()== HttpStatus.SC_OK) {//  data: ["xxxx", "xxxx"]
                return null;
            }

            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        return null;

    }
    
    public static void main(String[] args) throws UnirestException {
        HttpResponse<JsonNode> response;
        Map<String, Object> params = Maps.newHashMapWithExpectedSize(4);
        params.put("grant_type", "client_credentials");
        params.put("client_id", Const.APPID);
        params.put("client_secret", Const.SECRET);
        System.out.println(String.format("/%s/%s/users/%s/status", Const.ORG_NAME, Const.APP_NAME, "15021209494"));
//        String jsonObject = JSON.toJSONString(params);
//        response = Unirest.post("https://a1.easemob.com/1134161120115801/dudutest/token")
//        .header("accept", "application/json").body(jsonObject).asJson();
////        log.info("request get token with params {}, response {}", params, response);
//        if (response.getStatus()== HttpStatus.SC_OK) {
//            Token token = JSONObject.parseObject(response.getBody().getObject().toString(), Token.class);
//            System.out.print(token);
//        }
        
    }
}
